import React, { useState } from 'react';

function Quiz() {
  const questions = [
    {
      id: 1,
      question: "第一个单选题：请选择正确答案",
      options: ["A. 选项A", "B. 选项B", "C. 选项C", "D. 选项D"],
      correctAnswer: "B"
    },
    {
      id: 2,
      question: "第二个单选题：请选择正确答案",
      options: ["A. 选项A", "B. 选项B", "C. 选项C", "D. 选项D"],
      correctAnswer: "C"
    }
  ];

  const [selectedAnswers, setSelectedAnswers] = useState([]);

  const handleOptionChange = (questionId, answer) => {
    setSelectedAnswers((prevState) => {
      const updatedAnswers = [...prevState];
      const existingAnswerIndex = updatedAnswers.findIndex(answer => answer.questionId === questionId);
      
      if (existingAnswerIndex !== -1) {
        // 更新已有答案
        updatedAnswers[existingAnswerIndex].answer = answer;
      } else {
        // 添加新答案
        updatedAnswers.push({ questionId, answer });
      }
      
      return updatedAnswers;
    });
  };

  const handleSubmit = () => {
    // 在这里进行提交答案的操作，可以通过 AJAX 请求发送给服务器
    console.log(selectedAnswers);
  };

  return (
    <div>
      {questions.map((question) => (
        <div key={question.id}>
          <h1>{question.question}</h1>
          <div style={{ display: 'flex' }}>
            {question.options.map((option, index) => (
              <div key={index} style={{ marginRight: '10px' }}>
                <input
                  type="radio"
                  name={`answer-${question.id}`}
                  value={option}
                  checked={
                    selectedAnswers.some(
                      answer => answer.questionId === question.id && answer.answer === option
                    )
                  }
                  onChange={() => handleOptionChange(question.id, option)}
                />
                <label>{option}</label><br />
              </div>
            ))}
          </div>
        </div>
      ))}

      <br />
      <button onClick={handleSubmit}>提交答案</button>
    </div>
  );
}

export default Quiz;
